package com.yiwei.zxp.activity;

import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.widget.RecyclerView;
import android.text.Spanned;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.allen.library.SuperButton;
import com.yiwei.zxp.R;
import com.yiwei.zxp.adapter.GoodsDetailAdapter;
import com.yiwei.zxp.api.Api;
import com.yiwei.zxp.api.bean.GoodIdBean;
import com.yiwei.zxp.api.bean.GoodsAddBean;
import com.yiwei.zxp.api.model.GoodsDetailModel;
import com.yiwei.zxp.base.BaseActivity;
import com.yiwei.zxp.event.MainPacketEvent;
import com.yiwei.zxp.util.Dialog;
import com.yiwei.zxp.util.GlideImageLoader;
import com.yiwei.zxp.util.Network;
import com.yiwei.zxp.util.RxLifeUtil;
import com.yiwei.zxp.util.Spans;
import com.yiwei.zxp.util.ToastUtil;
import com.yiwei.zxp.util.UI;
import com.yiwei.zxp.view.FullyLinearLayoutManager;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.listener.OnBannerListener;

import org.greenrobot.eventbus.EventBus;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * Created by xsooy-pc on 17-12-8.
 */

public class GoodDetailsActivity extends BaseActivity {


    @BindView(R.id.btn_back)
    ImageView btnBack;
    @BindView(R.id.btn_share)
    ImageView btnShare;
    //    @BindView(R.id.pager_goods)
//    ViewPager pagerGoods;
//    @BindView(R.id.indicator)
//    LinePageIndicator indicator;

    @BindView(R.id.txt_goods_content)
    TextView txtGoodsContent;
    @BindView(R.id.txt_goods_info)
    TextView txtGoodsInfo;
    @BindView(R.id.txt_goods_address)
    TextView txtGoodsAddress;
    @BindView(R.id.txt_goods_type)
    TextView txtGoodsType;
    @BindView(R.id.txt_goods_param)
    TextView txtGoodsParam;
    @BindView(R.id.list_image)
    RecyclerView listImage;
    @BindView(R.id.scrollView)
    NestedScrollView scrollView;
    @BindView(R.id.btn_goods_down)
    SuperButton btnGoodsDown;
    @BindView(R.id.btn_goods_edit)
    SuperButton btnGoodsEdit;
    @BindView(R.id.btn_go_top)
    LinearLayout btnGoTop;
    @BindView(R.id.btn_params)
    LinearLayout btnParams;
    @BindView(R.id.btn_cancel)
    TextView btnCancel;
    @BindView(R.id.index_banner)
    Banner banner;
    @BindView(R.id.txt_goods_title)
    TextView txtGoodsTitle;
    private Unbinder unbiner;
    private GoodsDetailAdapter bottomAdapter;
    //    private ImagePagerAdapter adapter;
//    private List<ImageView> list;
    private int x24;
    private GoodsDetailModel.DatasBean totalData;
    private String good_id;
    private String goods_no;
//    private GoodsAddBean submitBean;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_goods_detail);
        initBar();
        unbiner = ButterKnife.bind(this);
        init();
    }

    private void init() {
        banner.setImageLoader(new GlideImageLoader());
        banner.setIndicatorGravity(BannerConfig.CENTER);
        x24 = getResources().getDimensionPixelSize(R.dimen.x24);
//        submitBean = new GoodsAddBean();
        good_id = getIntent().getStringExtra("goods_id");
        goods_no = getIntent().getStringExtra("goods_no");
        bottomAdapter = new GoodsDetailAdapter(this);
        FullyLinearLayoutManager mLayoutManager = new FullyLinearLayoutManager(this);
        listImage.setLayoutManager(mLayoutManager);
        listImage.setNestedScrollingEnabled(false);
        listImage.setAdapter(bottomAdapter);
        getGoodsDetail(good_id, goods_no);


    }

    public void getGoodsUp(String goods_id, String goods_no) {
        if (!Network.checkNetwork(this)) {
            ToastUtil.show(this, "网络连接失败");
            return;
        }

        loadingDialog.show();
        GoodIdBean bean = new GoodIdBean();
        bean.goods_id = goods_id;
        bean.goods_no = goods_no;
        Api.api_service.getGoodsShelve(bean).compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {
                        loadingDialog.dismiss();
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    showAddSuccessDialog();
                });
    }

    public void getGoodsDown(String goods_id, String goods_no) {
        if (!Network.checkNetwork(this)) {
            ToastUtil.show(this, "网络连接失败");
            return;
        }

        loadingDialog.show();
        GoodIdBean bean = new GoodIdBean();
        bean.goods_id = goods_id;
        bean.goods_no = goods_no;
        Api.api_service.getGoodsUnshelve(bean).compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {
                        loadingDialog.dismiss();
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    EventBus.getDefault().post(new MainPacketEvent("2"));
                    ToastUtil.makeText(this, "下架成功");
                    finish();
                });
    }


    public void getGoodsCancel(String goods_id, String goods_no) {
        if (!Network.checkNetwork(this)) {
            ToastUtil.show(this, "网络连接失败");
            return;
        }

        loadingDialog.show();
        GoodIdBean bean = new GoodIdBean();
        bean.goods_id = goods_id;
        bean.goods_no = goods_no;
        Api.api_service.getGoodsCancel(bean).compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {
                        loadingDialog.dismiss();
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    EventBus.getDefault().post(new MainPacketEvent("2"));
                    ToastUtil.makeText(this, "撤销成功");
                    finish();
                });
    }

    public void getGoodsDetail(String goods_id, String goods_no) {
        if (!Network.checkNetwork(this)) {
            ToastUtil.show(this, "网络连接失败");
            return;
        }

        loadingDialog.show();
        GoodIdBean bean = new GoodIdBean();
        bean.goods_id = goods_id;
        bean.goods_no = goods_no;
        Api.api_service.getGoodsDetail(bean).compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {
                        loadingDialog.dismiss();
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    totalData = result.datas;
                    setGoodsData(result.datas);
                });
    }


    private void showAddSuccessDialog() {
        Dialog.showDefaultDialog(this, "", "商品上架申请已提交请耐心等待平台审核", "", "好", false, new Dialog.DialogDefaultClickListener() {
            @Override
            public void confirm() {
                EventBus.getDefault().post(new MainPacketEvent("1"));
                ToastUtil.makeText(GoodDetailsActivity.this, "上架成功");
                finish();
            }

            @Override
            public void cancel() {

            }
        });
    }


    private void setGoodsData(GoodsDetailModel.DatasBean item) {

        banner.setImages(item.photos).start();


        Spanned txt_money = Spans.with(this).
                font("￥", x24, 0xffFF0030).style(Typeface.BOLD).
                font(item.price, getResources().getDimensionPixelSize(R.dimen.x48), 0xffFF0030).style(Typeface.BOLD).
                build();
        txtGoodsTitle.setText(txt_money);

        txtGoodsContent.setText(item.title);

        String fee = "";
        if (Float.valueOf(item.deliver_fee) == 0) {
            fee = "免运费";
            txtGoodsInfo.setTextColor(0xff999999);
        } else {
            fee = item.deliver_fee;
            txtGoodsInfo.setTextColor(0xffFF0030);
        }
        txtGoodsInfo.setText("快递：" + fee);
        txtGoodsAddress.setText(item.province + item.city);

        txtGoodsType.setText(item.cate_name);
        if (item.params != null && item.params.size() >= 0) {
            StringBuilder builder = new StringBuilder();
            for (int i = 0; i < item.params.size(); i++) {
                builder.append(item.params.get(i).name);
                builder.append("、");
            }
            txtGoodsParam.setText(builder.substring(0, builder.length() - 1));
//            if (item.params.size() == 1) {
//                txtGoodsParam.setText(item.params.get(0).name);
//            } else {
//                txtGoodsParam.setText(item.params.get(0).name + "...");
//            }
        }

        bottomAdapter.update(item.details);

        //状态（-1：审核不通过，0:待审核,1:正常出售中，2：下架）
        if (item.status.equals("0")) {
            btnCancel.setVisibility(View.VISIBLE);
            btnGoodsDown.setVisibility(View.GONE);
            btnGoodsEdit.setVisibility(View.GONE);
        } else if (item.status.equals("1")) {
            btnGoodsDown.setText("立即下架");
            btnGoodsDown.setShapeCornersRadius(getResources().getDimensionPixelSize(R.dimen.x40));
            btnGoodsDown.setUseShape();
            btnCancel.setVisibility(View.GONE);
            btnGoodsDown.setVisibility(View.VISIBLE);
            btnGoodsEdit.setVisibility(View.GONE);
        } else if (item.status.equals("2")) {
            btnGoodsDown.setText("立即上架");
            btnCancel.setVisibility(View.GONE);
            btnGoodsDown.setVisibility(View.VISIBLE);
            btnGoodsEdit.setVisibility(View.VISIBLE);
        }
    }


    public void scrollToPosition(int x, int y) {

        ObjectAnimator xTranslate = ObjectAnimator.ofInt(scrollView, "scrollX", x);
        ObjectAnimator yTranslate = ObjectAnimator.ofInt(scrollView, "scrollY", y);

        AnimatorSet animators = new AnimatorSet();
        animators.setDuration(1000L);
        animators.playTogether(xTranslate, yTranslate);
        animators.start();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbiner.unbind();
        unbiner = null;
    }

    @Override
    public void onStart() {
        super.onStart();
        banner.startAutoPlay();
    }

    @Override
    public void onStop() {
        super.onStop();
        banner.stopAutoPlay();
    }

    @OnClick({R.id.btn_check_all, R.id.btn_back, R.id.btn_cancel, R.id.btn_share, R.id.btn_goods_down, R.id.btn_goods_edit, R.id.btn_go_top})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_check_all:
                Dialog.showGoodsParams(this, totalData.params);
                break;
            case R.id.btn_back:
                finish();
                break;
            case R.id.btn_cancel:
                Dialog.showDefaultDialog(this, "", "确定撤销该商品？", "取消", "确定", false, new Dialog.DialogDefaultClickListener() {
                    @Override
                    public void confirm() {
                        getGoodsCancel(good_id, goods_no);
                    }

                    @Override
                    public void cancel() {

                    }
                });
                break;
            case R.id.btn_share:
                break;
            case R.id.btn_goods_down:
                if (UI.toString(btnGoodsDown).equals("立即下架")) {
                    Dialog.showDefaultDialog(this, "", "确定下架该商品？", "取消", "确定", false, new Dialog.DialogDefaultClickListener() {
                        @Override
                        public void confirm() {
                            getGoodsDown(good_id, goods_no);
                        }

                        @Override
                        public void cancel() {

                        }
                    });
                } else if (UI.toString(btnGoodsDown).equals("立即上架")) {
                    Dialog.showDefaultDialog(this, "", "确定上架该商品？", "取消", "确定", false, new Dialog.DialogDefaultClickListener() {
                        @Override
                        public void confirm() {
                            getGoodsUp(good_id, goods_no);
                        }

                        @Override
                        public void cancel() {

                        }
                    });
                }

                break;
            case R.id.btn_goods_edit:
                Intent intent = new Intent(this, GoodsAddActivity.class);
                intent.putExtra("data", totalData);
                startActivity(intent);
                overridePendingTransition(R.anim.right_enter, R.anim.left_out);
                break;
            case R.id.btn_go_top:
                scrollView.post(new Runnable() {
                    @Override
                    public void run() {
                        scrollToPosition(0, 0);
                    }
                });
                break;
        }
    }
}
